from utils.object_utils import cache
from setting import BASE_URL
import requests
from loguru import logger

"""
作用 ： 为所有接口提供公共功能 ，方便接口调用。
具体功能:
    1. 返回完整的url地址
    2. 重新封装get，post请求
    3. 处理请求头
"""

class Base:

    def get_url(self,path,params=None):
        """
        返回一个完整的URL ：http://ip:port/api?params
        :param path: 接口地址
        :param params: 查询参数
        :return:
        """
        if params:
            full_path = BASE_URL + path + "?" + params
            return full_path
        return BASE_URL + path



    def get(self,url):
        """
        重新封装get方法
        (1). 加上日志 ：loguru
        (2). 加入异常 : try ... expect
        :return:
        """
        result = None
        response = requests.get(url,headers=self._get_headers())
        try:
            result = response.json()     # 返回的是响应体
            logger.success("请求URL:{},返回结果:{}".format(url,result))
            return result
        except Exception as e:
            logger.error("请求get方法异常，返回数据{}".format(result))

    def post(self,url,data):
        result = None
        response = requests.post(url,json=data,headers=self._get_headers())
        try:
            result = response.json()
            logger.success("请求URL:{},返回结果:{}".format(url,result))
            return result
        except Exception as e:
            logger.error("请求post方法异常，返回数据{}".format(result))

    def _get_headers(self):
        headers = {"Content-Type":"application/json"}
        token = cache.get('token')
        if token:
            headers.update({'X-Litemall-Admin-Token':token})
            return headers
        return headers


if __name__ == '__main__':
    base = Base()
    print(base.get_url('/admin/auth/login'))
    print(base.get_url('/admin/admin/list','page=1&limit=20&sort=add_time&order=desc'))
    url = base.get_url('/admin/admin/list','page=1&limit=20&sort=add_time&order=desc')
    print(base.get(url))